package com.examples.gateway.helper.filter;

import com.examples.core.req.ExamHeader;
import com.examples.gateway.common.CheckState;
import com.examples.gateway.entity.SystemPermission;
import com.examples.gateway.helper.Constants;
import com.examples.gateway.service.ExamPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 校验用户是否有指定API的权限
 * @author Dai YaLu
 */
@Slf4j
public class ApiAuthorityFilter extends AbstractGlobalHelperFilter{

    @Autowired
    private ExamPermissionService airPermissionService;

    @Override
    public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ExamHeader user = exchange.getAttribute(Constants.EXAMPLES_GATEWAY_USER_DETAIL);
        SystemPermission permission = exchange.getAttribute(Constants.EXAMPLES_GATEWAY_CHECK_PERMISSION);
        if(null == user){
            return handleError(exchange, CheckState.API_AUTHORITY);
        }
        if (validate(user, permission)) {
            return chain.filter(exchange);
        } else {
            return handleError(exchange, CheckState.API_AUTHORITY);
        }
    }

    private boolean validate(ExamHeader user, SystemPermission permission) {
        List<SystemPermission> list = airPermissionService.list(user.getUserId());
        long c = list.stream().filter(item -> item.getId().equals(permission.getId())).count();
        return c > 0;
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
